import request from '@/utils/request';
import {setToken, removeToken} from '@/utils/auth';

// 注册
export const userRegister = ({commit}, data) => {
  return request({
    url: '/user/register',
    method: 'post',
    data: data
  });
};

// 前台用户登录
export const userLogin = ({commit}, data) => {
  return request({
    url: '/user/login',
    method: 'post',
    data: data
  });
};

// 获取用户信息
export function getUserInfo () {
  return request({
    url: '/user/info',
    method: 'get'
  });
}

// 登出
export function userlogout () {
  return request({
    url: '/user/logout'
  });
}

// 登录
export function login ({commit}, userInfo) {
  const {account, password, rememberMe} = userInfo;
  return new Promise((resolve, reject) => {
    userLogin('userLogin', {account: account.trim(), password: password, rememberMe: rememberMe}).then(response => {
      const {data} = response;
      commit('SET_TOKEN_STATE', data.token);
      setToken(data.token);
      resolve(data);
    }).catch(error => {
      reject(error);
    });
  });
}

// 获取用户信息
export function getInfo ({commit}) {
  return new Promise((resolve, reject) => {
    getUserInfo().then(response => {
      const {data} = response;
      if (!data) {
        commit('SET_TOKEN_STATE', '');
        commit('SET_USER_STATE', '');
        this.removeToken();
        resolve();
        reject(new Error('Verification failed, please Login again.'));
      }
      commit('SET_USER_STATE', data);
      resolve(data);
    }).catch(error => {
      reject(error);
    });
  });
}

// 注销
export function logout ({commit, state}) {
  return new Promise((resolve, reject) => {
    userlogout()
      .then((response) => {
        commit('SET_TOKEN_STATE', '');
        commit('SET_USER_STATE', '');
        removeToken();
        resolve();
      })
      .catch((error) => {
        reject(error);
      });
  });
}

// 获取抢购商品信息
export const loadSeckillsInfo = ({commit}, storeId) => {
  return new Promise((resolve, reject) => {
    request({
      url: '/seckill/info',
      method: 'get',
      params: {
        storeId: storeId
      }
    }).then((value) => {
      const {data} = value;
      commit('SET_SECKILLS_INFO', data);
    });
  });
};

// 获取抢购倒计时
export const loadSeckillsTime = ({commit}) => {
  return new Promise((resolve, reject) => {
    const date = new Date();
    const minute = 60 - date.getMinutes();
    const seconds = 60 - date.getSeconds();
    // 距离开始秒杀时间
    const deadline = {
      hours: 1,
      minute: minute,
      seconds: seconds
    };
    commit('SET_SECKILLS_TIME', deadline);
  });
};

// 获取快速导航界面图标
export const loadServiceItems = ({commit}) => {
  return new Promise((resolve, reject) => {
    const data = {
      serviceItems:
        [
          {
            route: '/store',
            img: 'static/img/index/icon/location1.svg',
            title: '附近门店'
          },
          {
            route: '/shoppingCart',
            img: 'static/img/index/icon/cart1.svg',
            title: '购物车'
          },
          {
            route: '/coupon',
            img: 'static/img/index/icon/coupon2.svg',
            title: '优惠券'
          },
          {
            route: '/orderList',
            img: 'static/img/index/icon/order_cute.svg',
            title: '历史订单'
          },
          {
            route: '/pointShop',
            img: 'static/img/index/icon/shop1.svg',
            title: '积分商城'
          },
          {
            route: '/',
            img: 'static/img/index/icon/user3.svg',
            title: '用户中心'
          }
        ],
      userInfo: {
        img: 'static/img/index/icon/user2.svg',
        userName: 'luckku'
      }
    };
    commit('SET_SERVICE_INFO', data);
  });
};

// 获取轮播(营销)图片
export const loadCarouselItems = ({commit}) => {
  return new Promise((resolve, reject) => {
    const data = {
      carouselItems: [
        'static/img/nav/1.jpg',
        'static/img/nav/2.jpg',
        'static/img/nav/3.jpg',
        'static/img/nav/4.jpg',
        'static/img/nav/5.jpg'
      ]
    };
    commit('SET_CAROUSELITEMS_INFO', data);
  });
};

// 加载商品数据
export const loadEat = ({commit}) => {
  return new Promise((resolve, reject) => {
    request({
      url: '/goods/list',
      method: 'get'
    }).then((value) => {
      const {data} = value;
      commit('SET_EAT_INFO', data);
    });
  });
};

// 加载领券中心
export const loadCouponCenterList = ({commit}) => {
  return new Promise((resolve, reject) => {
    request({
      url: '/coupon/availableCouponList',
      method: 'get'
    }).then((value) => {
      const {data} = value;
      commit('SET_COUPON_CENTER', data);
    });
  });
};

// 加载用户优惠券
export const loadCoupon = ({commit}, userId) => {
  return new Promise((resolve, reject) => {
    request({
      url: '/coupon/userCoupon?userId=' + userId,
      method: 'get'
    }).then((value) => {
      const couponList = value.data;
      commit('SET_COUPON', couponList);
    });
  });
};

// 加载用户优惠券
export const loadUsableCoupon = ({commit}, idSet) => {
  return new Promise((resolve, reject) => {
    console.log(idSet);
    request({
      url: '/coupon/usableCoupon',
      method: 'get',
      params: {
        userId: idSet[0],
        totalPrice: idSet[1]
      }
    }).then((value) => {
      const couponList = value.data;
      commit('SET_COUPON', couponList);
    });
  });
};

// 加载用户购物车
export const loadShoppingCart = ({commit}, idSet) => {
  return new Promise((resolve, reject) => {
    request({
      url: '/cart/userCart',
      method: 'get',
      params: {
        userId: idSet[0],
        storeId: idSet[1]
      }
    }).then((value) => {
      const cart = value.data;
      commit('SET_SHOPPING_CART', cart);
      loadUsableCoupon({commit}, [idSet[0], cart.totalPrice]);
    });
  });
};

// 加载用户购物车
export const cleanCart = ({commit}, idSet) => {
  return new Promise((resolve, reject) => {
    request({
      url: '/cart/cleanCart',
      method: 'delete',
      params: {
        userId: idSet[0],
        storeId: idSet[1]
      }
    }).then(() => {
      const cart = [];
      commit('SET_SHOPPING_CART', cart);
    });
  });
};

// 生成订单
export const generateOrder = ({commit}, idSet) => {
  return request({
    url: '/order/generateOrder',
    method: 'post',
    params: {
      userId: idSet[0],
      storeId: idSet[1],
      couponId: idSet[2]
    }
  });
};

// 設置店鋪id
export const setStoreId = ({commit}, storeId) => {
  return new Promise((resolve, reject) => {
    commit('SET_STORE_ID', storeId);
  });
};

export const loadAddress = ({commit}) => {
  return new Promise((resolve, reject) => {
    const address = [
      {
        addressId: '123456',
        name: 'Luckku',
        province: '浙江省',
        city: '杭州市',
        area: '临安区',
        address: '杭州电子科技大学信息工程学院',
        phone: '152****0609',
        postalcode: '123456'
      },
      {
        addressId: '123458',
        name: 'Bob',
        province: '上海市',
        city: '上海市',
        area: '浦东新区',
        address: '沙新镇',
        phone: '158****0888',
        postalcode: '654321'
      }
    ];
    commit('SET_USER_ADDRESS', address);
  });
};

// 加载订单
export const loadOrderList = ({commit}) => {
  return new Promise((resolve, reject) => {
    request({
      url: '/order/getOrderList',
      method: 'get'
    }).then((value) => {
      const orderList = value.data;
      commit('SET_ORDER_LIST', orderList);
    });
  });
};

// 获取附近门店
export const loadStore = ({commit}) => {
  return new Promise((resolve, reject) => {
    request({
      url: '/store/getStoreList',
      method: 'get'
    }).then((value) => {
      const {data} = value;
      commit('SET_STORE', data);
    });
  });
};

// 获取当前门店信息
export const getStoreInfo = ({commit}, storeId) => {
  return new Promise((resolve, reject) => {
    request({
      url: '/store/getStoreInfo',
      method: 'get',
      params: {
        storeId: storeId
      }
    }).then((value) => {
      const {data} = value;
      commit('SET_STORE_INFO', data);
    });
  });
};
